package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import models.ActionLog;
import models.QueryBean;
import play.mvc.Controller;
import play.mvc.With;
import controllers.Secure;
import controllers.ValidationUtil;

@With(Secure.class)
public class ActionLogs extends Controller {

	public static void index(){
		render();
	}
	
	public static void indexTable(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
			queryBean.isDesc = true;
		}
		StringBuilder hql = new StringBuilder("id != null ");
    	List<Object> objs = new ArrayList<Object>();
    	
    	if(!ValidationUtil.isEmpty(queryBean.keyword)) {
    		if(ValidationUtil.isLong(queryBean.keyword)) {
    			hql.append("and (id=? or ");
        		objs.add(queryBean.keyword);
        		
        		hql.append(" objectId=? or ");
        		objs.add(queryBean.keyword);
    		} else {
    			hql.append("and (");
    		}
    		hql.append("objectType like ? or actionType like ? or " +
    				"comment like ? or createByAdmin.username like ?) ");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    	}
    	
    	if(!ValidationUtil.isEmpty(queryBean.orderby)) {
    		hql.append(" order by " + queryBean.orderby);
    		if(queryBean.isDesc) 
    			hql.append(" desc ");
    		else
    			hql.append(" asc ");
    	} else {
    		hql.append(" order by createAt desc, lastModifiedAt desc ");
    	}
		
		//页数计算
		queryBean.totalQuantity = ActionLog.count(hql.toString(), objs.toArray());
		queryBean.totalPage = (queryBean.totalQuantity/queryBean.quantityEachPage + 1);
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		
		List<ActionLog> actionLogs = ActionLog.find(hql.toString(), objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		
		render(actionLogs, queryBean);
	}
	
	/**
	 * 删除指定Log。
	 */
	public static void deleteActionLog(long id) {
		ActionLog actionLog = ActionLog.findById(id);
		if(actionLog == null) return;
		actionLog.delete();
	}
}
